import babelpolyfill from 'babel-polyfill'
import Vue from 'vue'
import App from './App'
import ElementUI from 'element-ui'
import 'element-ui/lib/theme-chalk/index.css'
//import './assets/theme/theme-green/index.css'
import VueRouter from 'vue-router'
import store from './vuex/store'
import Vuex from 'vuex'
//import NProgress from 'nprogress'
//import 'nprogress/nprogress.css'
import routes from './routes'
// import Mock from './mock'
// Mock.bootstrap();
// import 'font-awesome/css/font-awesome.min.css'
import axios from "axios";



axios.interceptors.request.use(config => {
  if (config.url !== "/login" && config.url !== "/loginOut") {
    let token = sessionStorage.getItem("token");
    if (token) {
      config.headers.token = token;
    }
    return config;
  }
}, error => {
  return Promise.reject(error)
})

axios.interceptors.response.use(response => {
  let status = response.status;
  let {success, message} = response.data;
  console.log("status ==> ",status)
  console.log("message ==> ",message)
  if (status !== 200) {
    if (status === 401) {
      ElementUI.Message({
        message: "请先登录",
        type: "warning",
        showClose: true
      });
      router.push("/login");
    }
    else if (status === 403) {
      router.push("/noPermission");
      ElementUI.Message({
        message: "操作未授权",
        type: "warning",
        showClose: true
      });
    }
    else if (status === 404) {
      console.log("404页面")
      router.push("/404");
      ElementUI.Message({
        message: "资源未找到",
        type: "warning",
        showClose: true
      });
    }
  }
  return response;
}, error => {

 /* let message;
  if (error.data.message === "操作失败") {
    message = "请求异常"
  } else {
    message = error.data.message;
  }
  ElementUI.Message({
    message: message,
    type: "warning",
    showClose: true
  });*/

  return Promise.reject(error);
})



axios.defaults.baseURL = '/api'
Vue.prototype.$http = axios

Vue.use(ElementUI)
Vue.use(VueRouter)
Vue.use(Vuex)


//NProgress.configure({ showSpinner: false });

const router = new VueRouter({
  routes
})

// 前置拦截
router.beforeEach((to, from, next) => {
  //NProgress.start();
  let user = sessionStorage.getItem('user');
  let token = sessionStorage.getItem('token');

  if (to.path === '/login') {
    // sessionStorage.removeItem('user');
    // sessionStorage.removeItem('token');
    if (user && token) {
      next({path: '/'})
    }
  }
  if ((!user || !token) && to.path !== '/login') {
    next({ path: '/login' })
  } else {
    next()
  }

  if (from.path === '/login' && JSON.stringify(user).user === "admin") {
    next({path: '/'})
  }
})

//router.afterEach(transition => {
//NProgress.done();
//});

new Vue({
  //el: '#app',
  //template: '<App/>',
  router,
  store,
  //components: { App }
  render: h => h(App)
}).$mount('#app')


